﻿using System;
using Castle.MonoRail.Framework;
using Hadlow.Jobvertizer.Models;
using Hadlow.Jobvertizer.Repositories;
using Hadlow.Jobvertizer.HtmlHelpers;
using Castle.MonoRail.Framework.Helpers;

namespace Hadlow.Jobvertizer.Controllers
{
    public class JobSearchController : BaseController
    {
        readonly int pageSize;

        readonly IJobRepository jobRepository;
        readonly ILocationRepository locationRepository;

        public JobSearchController(
            IJobRepository jobRepository,
            ILocationRepository locationRepository,
            int pageSize)
        {
            this.jobRepository = jobRepository;
            this.locationRepository = locationRepository;
            this.pageSize = pageSize;
        }

        public void List([DataBind("criteria")] JobSearchCriteria criteria)
        {
            // have to get the full location tree
            if (criteria.Location == null) criteria.Location = new Location() { Id = 1 };
            if (criteria.Location.Id == 0) criteria.Location.Id = 1;
            criteria.Location = locationRepository.GetForId(criteria.Location.Id);

            Job[] jobs = jobRepository.Search(criteria);
            IPaginatedPage paginatedJobs = PaginationHelper.CreatePagination<Job>(this, jobs, pageSize);
            PropertyBag["jobs"] = paginatedJobs;
            PropertyBag["criteria"] = criteria;
        }
    }
}
